<?php
/**
 * Created by PhpStorm.
 * User: 墨鱼行
 * Signature: 好好学习，天天向上
 * Date: 19-2-18
 * Time: 下午3:18
 */

namespace app\lib\exception;


use think\exception\Handle;
use think\facade\Log;
use think\facade\Request;

class ExceptionHandler extends Handle
{
    private $code, $errorCode, $msg;

    /**
     * 重写render方法（需要修改配置文件exception_handle）
     *
     * @param Exception $e
     * @return \think\Response|\think\response\Json
     */
    public function render (\Exception $e)
    {
        if ($e instanceof BaseException)
        {
            $this->code      = $e->code;
            $this->errorCode = $e->errorCode;
            $this->msg       = $e->msg;
        }
        else
        {
            if (config('app_debug'))
            {
                return parent::render($e);
            }
            else
            {
                $this->code      = 500;
                $this->errorCode = 999;
                $this->msg       = '服务器内部错误';
                $this->recordErrorLog($e);
            }
        }
        $request = Request::instance();
        $result = [
            'msg'       => $this->msg,
            'errorCode' => $this->errorCode,
            'url'       => $request->url()
        ];

        return json($result, $this->code);
    }

    /**
     * 记录错误日志
     *
     * @param Exception $e
     */
    private function  recordErrorLog(\Exception $e)
    {
        Log::record($e->getMessage(), 'error');
    }
}